<template>
  <el-dialog
    :visible="visible"
    :title="$t('fmeaProject.submitApprove')"
    width="1000px"
    :close-on-click-modal="false"
    :before-close="close"
    @close="onClose"
    @open="onOpen"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <div style="height: calc(100vh - 360px);padding-right:10px;overflow: auto">
          <el-form ref="elForm" v-loading="loading" :model="formData" size="medium" label-position="top">
            <el-form-item v-if="visibleUpgrade" size="small" :label="$t('fmeaProject.upgrade')" prop="variables.versionType">
              <el-radio-group v-model="formData.variables.versionType" size="medium" @change="changeVersionType">
                <el-radio
                  v-for="(item, index) in versionTypeOptions"
                  :key="index"
                  :label="item.value"
                  :disabled="item.disabled"
                >{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item size="small" :label="$t('fmeaProject.versionNumber')" prop="variables.version">
              <el-input disabled v-model="formData.variables.version" />
            </el-form-item>
            <!-- 审批节点 -->
            <el-form-item
              v-for="(item,index) in approvalNodes"
              :key="index"
              size="small"
              :label="item.name"
              :prop="'variables.' + item.key"
              :rules="{required: true, message:item.name + $t('fmeaProject.canNotBeEmpty'),trigger: 'change,blur', type: item.multiple ? 'array' : 'string'}"
            >
              <!-- 自定义节点根据Key获取用户 -->
              <template v-if="item.isCustomNode">
                <el-select
                  v-model="formData.variables[item.key]"
                  :multiple="item.multiple"
                  filterable
                  clearable
                  style="width: 100%"
                  :disabled="disabledForm"
                >
                  >
                  <el-option v-for="item2 in approvalUser[item.key]" :key="item2.userId" :value="item2.userId" :label="item2.userName" />
                  <el-option v-for="item2 in approvalUser[item.key]" :key="item2.userId" :value="item2.userId" :label="item2.userName" />
                </el-select>
              </template>
              <!-- 非自定义节点获取所有用户 -->
              <template v-else>
                <select-user v-model="formData.variables[item.key]" :multiple="item.multiple" filterable style="width: 100%" :disabled="disabledForm" />
              </template>
            </el-form-item>
            <el-form-item
              size="small"
              :label="$t('fmeaProject.amendmentsAndReasons')"
              prop="variables.description"
              :rules="{min: 0, max: 1000, message: $t('fmeaProject.theRevisedContentAndReasonsAreTooLong'),trigger: 'blur'}"
            >
              <el-input
                v-model="formData.variables.description"
                type="textarea"
                :placeholder="$t('fmeaProject.pleaseInputAmendmentsAndReasons')"
                :autosize="{minRows: 4, maxRows: 4}"
                :style="{width: '100%'}"
              />
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="draft-title">{{ $t('approve.unapprovedKnowledge') }}</div>
        <el-table stripe :data="knowDraftData" border height="calc(100vh - 400px)">
          <el-table-column type="index" :label="$t('approve.index')" align="center" width="60" />
          <el-table-column prop="code" :label="$t('approve.code')" align="center" min-width="110" />
          <el-table-column prop="description" :label="$t('approve.desc')" header-align="center" min-width="140" />
          <el-table-column prop="knowledgeType" :label="$t('approve.knowledgeType')" align="center" min-width="160" show-overflow-tooltip />
        </el-table>
      </el-col>
    </el-row>
    <div slot="footer">
      <el-button size="mini" @click="close">{{ $t('fmeaProject.cancel') }}</el-button>
      <el-button size="mini" type="primary" @click="handleConfirm">{{ $t('fmeaProject.submit') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { getNexNode, initiateApproval, getApprover } from '@/api/fmea/common/approve'
import { getGroupUserList } from '@/api/fmea/common/project'
import { checkProjectKnow, checkRelation, projectKnowDraft } from '@/api/fmea/common/approve'
import SelectUser from '@/views/components/Select/SelectUser'

// 提交审批弹出框 PFMEA、DFMEA、MFMEA通用
export default {
  name: 'LaunchProcessDialog',
  components: { SelectUser },
  dicts: ['project_approve', 'approve_type'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // appId,projectId,version
    params: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示升级
      visibleUpgrade: true,
      // 审批节点
      approvalNodes: [],
      // 自定义审批节点用户数据
      approvalUser: {},
      // 表单数据
      formData: {
        businessKey: null,
        variables: {
          version: null,
          versionType: 1,
          description: null
        }
      },
      // 版本升级选项
      versionTypeOptions: [{
        value: 1,
        label: this.$t('fmeaProject.bigVersion')
      }, {
        value: 2,
        label: this.$t('fmeaProject.smallVersion')
      }],
      disabledForm: false,
      knowDraftData: []
    }
  },
  methods: {
    // 提交
    handleConfirm() {
      checkProjectKnow(this.params.projectId).then(resKnow => {
        if (!resKnow.data) {
          this.$message.error(this.$t('approve.errorTipUnapproved'))
        } else {
          checkRelation(this.params.projectId).then(resRelation => {
            if (!resRelation.data) {
              this.$message.error(this.$t('approve.errorTipNoRelationship'))
            } else {
              this.submit()
            }
          })
        }
      })
    },
    submit() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          this.loading = true
          this.formData.variables.projectId = this.params.projectId
          initiateApproval(this.formData).then(() => {
            this.$emit('save-success')
            this.$modal.msgSuccess(this.$t('fmeaProject.submittedSuccessfully'))
            this.loading = false
            this.close()
          })
        }
      })
    },
    // 切换版本升级选项
    changeVersionType() {
      this.formData.variables.version = this.versionUpgrade(this.params.version, this.formData.variables.versionType)
    },
    // 版本升级
    versionUpgrade(value, versionType) {
      if (value) {
        const version = parseFloat(value.slice(2, value.length))
        return versionType === 1 ? 'V0' + Math.floor(version + 1).toFixed(2) : 'V0' + (version + 0.01).toFixed(2)
      } else {
        return 'V01.00'
      }
    },
    // 获取未审批的知识
    getKnowDraft() {
      this.knowDraftData = []
      projectKnowDraft(this.params.projectId).then((resDraft) => {
        this.knowDraftData = resDraft.data
      })
    },
    // 获取审批节点
    getApprovalNodes() {
      getNexNode({ id: this.formData.key }).then(res => {
        const items = res.data
        const approvalNodes = []
        if (items && items.length > 0) {
          // 格式化审批节点数据
          items.forEach(io => {
            const item = { name: io.name }
            if (io.loopCharacteristics) {
              // 多选取值
              item.key = io.loopCharacteristics.inputDataItem
              item.multiple = true
            } else {
              // 单选取值 ${XXX}
              item.key = io.assignee.slice(2, io.assignee.length - 1)
              item.multiple = false
            }

            // 判断是否为自定义节点（自定义节点获取项目内用户数据）
            item.isCustomNode = !!this.selectDictLabel(this.dict.type.approve_type, item.key)

            approvalNodes.push(item)
          })
        }

        this.approvalNodes = approvalNodes

        // 获取审批节点数据(如果存在存在未结束节点，则回显数据)
        getApprover({ businessKey: this.params.projectId }).then(res => {
          if (res.data) {
            approvalNodes.forEach(({ key }) => {
              if (res.data[key]) { this.$set(this.formData.variables, key, res.data[key]) }
            })
          } else {
            approvalNodes.forEach(item => {
              if (item.multiple) {
                this.formData.variables[item.key] = []
                this.approvalUser[item.key].forEach(t => {
                  this.formData.variables[item.key].push(t.userId)
                })
              } else {
                this.$set(this.formData.variables, item.key, this.approvalUser[item.key][0].userId)
              }
            })
          }
        })
      })
    },
    // 获取审批人员
    getApprovalUser() {
      return getGroupUserList({ projectId: this.params.projectId }).then(res => {
        this.approvalUser = res.data
      })
    },
    // 获取审批节点数据
    getApprovalNodeData() {
      const variables = this.formData.variables
      getApprover({ businessKey: this.params.projectId }).then(res => {
        if (res.data) {
          this.approvalNodes.forEach(({ key }) => {
            if (res.data[key]) {
              variables[key] = res.data[key]
            }
          })
          this.disabledForm = true
        }
      })
    },
    // 窗口打开
    onOpen() {
      this.getKnowDraft()
      this.formData.businessKey = this.params.projectId
      this.formData.key = this.selectDictLabel(this.dict.type.project_approve, this.params.appId)
      // 初始化版本号
      this.visibleUpgrade = !!this.params.version
      this.changeVersionType()
      // 获取审批人员
      this.getApprovalUser().then(res => {
        // 获取审批节点
        this.getApprovalNodes()
      })
    },
    // 窗口关闭
    onClose() {
      this.approvalNodes = []
      this.approvalUser = {}
      this.$refs.elForm.resetFields()
      this.formData.variables = {
        version: null,
        versionType: 1,
        description: null
      }
      this.disabledForm = false
    },
    // 窗口关闭前执行
    close() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
  .draft-title{
    height: 44px;
    line-height: 32px;
    position: relative;
    &:before{
      content: '';
      display: inline-block;
      width: 2px;
      height: 16px;
      background: #{'var(--current-color)'};
      margin-right: 4px;
      vertical-align: middle;
      margin-top: -2px;
    }
  }
</style>
